#!/bin/bash
#
# Copyright 2007,2008 Kaio Rafael de Souza Barbosa
# kaiorafael@gmail.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ---------------------------------------------------------
# This Script helps the Subversion Administrations Tasks
# If you want to integrate Apache2 + SVN 
#
# Please, if you need more information about Apache2 and SVN
# read Subversion's Book at
# http://svnbook.red-bean.com/en/1.4/svn.serverconfig.httpd.html
# http://svnbook.red-bean.com/


# Before Use mysvnadmin, please configure it 
# At: /etc/mysvnadmin/mysvnadmin.conf

. /etc/mysvnadmin/mysvnadmin.conf

# Internal Variables
version=0.3.9.3
LN=$(which ln)

# Functions

#
# Help Function
#
usage(){
	echo
	echo "usage: $(basename $0) [options]"
	echo
	echo "Options:"
	echo " "
	echo -e "-c repository \t\t : Create a Subversion repository"
	echo -e "-t template [default|ldap]: Create a repository using a APACHE_TEMPLATE"
	echo -e "-a username \t\t : Add a user into apache"
	echo -e "-g username \t\t : Same as -a, but system generate a password"
	echo -e "-P project name \t : Repository name"
	echo -e "-G group Name \t\t : SVN group name"
	echo -e "-U username \t\t : Username"
	echo -e "-A ADD \t\t\t : Add a user into a SVN group"
	echo -e "-h \t\t\t : Print this help"
	echo -e "-v \t\t\t : Print mysvnadmin version"
	echo " "

	echo "Examples:"
	echo
	echo "1) Create a Apache2 based repository"
	echo "mysvnadmin -c FSF -t default"
	echo
	echo "2) Add a user with generated password"
	echo "mysvnadmin -g tux"
	echo
	echo "3) Add a user into SVN group"
	echo "mysvnadmin -P FSF -G develop -U tux -A"

	echo
}


###############################################
# Section: Create Repository
#
# creating SVN repository using svnadmin
###############################################
#
# Create Repository Function
#
CreateSVNRepos(){
SVN_REPOS=$1 # Get first parameter
APACHE_TEMPLATE=$2 # Get second parameter

	# Check if $SVN_REPOS exist

	if [ -d ${SVN_ROOT_HOME}/${SVN_REPOS} ];then
		echo "Repository ${SVN_REPOS} already exist"
		exit 1

		else

		if `${SVN_ADM_CMD} create ${SVN_ROOT_HOME}/${SVN_REPOS}` ; then
			echo
			echo "Repository: ${SVN_REPOS}, successfully created!"
			else
			echo "Error to create: ${SVN_REPOS}"
			exit 1
		fi
	fi

#
# Change permisson from DAV, LOCK e DB
#

echo "Changing permisson from dav, lock and db"

chmod g+w  ${SVN_ROOT_HOME}/${SVN_REPOS}/dav \
 ${SVN_ROOT_HOME}/${SVN_REPOS}/locks  ${SVN_ROOT_HOME}/${SVN_REPOS}/db

chmod g+s  ${SVN_ROOT_HOME}/${SVN_REPOS}/dav \
 ${SVN_ROOT_HOME}/${SVN_REPOS}/locks  ${SVN_ROOT_HOME}/${SVN_REPOS}/db

chown -R ${APACHE_USER}:${APACHE_GROUP} ${SVN_ROOT_HOME}/${SVN_REPOS}/dav
chown -R ${APACHE_USER}:${APACHE_GROUP} ${SVN_ROOT_HOME}/${SVN_REPOS}/locks
chown -R ${APACHE_USER}:${APACHE_GROUP} ${SVN_ROOT_HOME}/${SVN_REPOS}/db


###############################################
# Section: Apache Templates
#
# generating new apache2 APACHE_TEMPLATE output
###############################################
#
#  SVN Permisson Output
#

cat  ${AUTHSVN_PERMISSION_TEMPLATE_FILE} \
 > ${SVN_ACCESS_DIR}/${SVN_REPOS}

#
# Apache Template
#

if [ "$APACHE_TEMPLATE" = default ];then

	. ${DEFAULT_APACHE_TEMPLATE_FILE} > $SVN_TMP
fi

# 
# LDAP Template
#

if [ "$APACHE_TEMPLATE" = "ldap" ]; then

	. ${MSLDAP_APACHE_TEMPLATE_FILE} > $SVN_TMP

fi


#
# Generating all Apache2 configuration
#

echo "You can find this project at: ${APACHE_PROJECT_CONF}"

cat $SVN_TMP >> ${APACHE_PROJECT_CONF}/${SVN_REPOS}

if [ ! -f ${APACHE_SERVER_CONF}/${SVN_REPOS} ];then
	echo "I'll create the apache2 server symlink"
	echo
	${LN} -s ${APACHE_PROJECT_CONF}/${SVN_REPOS} ${APACHE_SERVER_CONF}/${SVN_REPOS}
	else
		echo "Error creating a symlink to ${APACHE_SERVER_CONF}/${SVN_REPOS}"
		echo "Please check your Apache2 server configuration"
		exit 1
fi

echo "You need to restart or reload your apache2 server!!!"


}


###############################################
# Section: Apache User Administration
#
# search, add and create a apache2 user
###############################################
#
# Search Apache user function
#
SearchApacheUser() {
 	if [ "$(cut -f1 -d: ${SVN_PASS_FILE} | grep "\<${1}\>" )" = $1 ]; then
		echo "User: $1, already exist"
		exit 1
	fi
}

#
# Add Apache user function into Apache password file
#
AddApacheUser(){
	SearchApacheUser $1
	echo "Creating User: $1"
	${APACHE_HTPASS_CMD} ${SVN_PASS_FILE} $1
}

#
# Add a Apache user with a generated password
#
AddApacheUserGenpass(){
	SearchApacheUser $1
	echo "Creating User: $1"
	${APACHE_HTPASS_CMD} -b ${SVN_PASS_FILE} $1 ${AUTO_PASSWD}
	echo "User $1 password is: ${AUTO_PASSWD}"
}


###############################################
# Section: AuthSVN User Administration
#
# search, add and create a apache2 user
###############################################
#
# Function to find a group into permission svn file
#

# SearchSVNGroup needs 2 parameters
# $1 project name
# $2 group name
SearchSVNGroup(){
if  `grep "\<${2}\>" ${SVN_ACCESS_DIR}/${1} >/dev/null` ;then
        : # this is ugly, i know!
        else
                echo "Group: ${2} not found"
                exit 1
fi
}

#
# Add a user into svn group
# 3 parameters are necessary
# $1 project name
# $2 group name
# $3 user name
AddUserSVNGroup(){

if [ $# -ne 3 ];then
	echo "You need to use -P -G -U together"
	echo "mysvnadmin -P project -G group -U user -A"
	exit 1

	elif [ ! -f ${APACHE_PROJECT_CONF}/${1} ];then
		echo "There is no such project: ${1}"
		exit 1
	else
        	SearchSVNGroup $1 $2
fi

if `grep "\<${2}\>" ${SVN_ACCESS_DIR}/${1} | grep "${3}" >/dev/null`; then
       	echo "User $3 is already on group $2"
	else
                #Change line where group is found
                sed "/^${2}/s/$/, ${3}/;s/=\,/=/" ${SVN_ACCESS_DIR}/${1} > \
			${SVN_ACCESS_DIR}/${1}.org

                cp ${SVN_ACCESS_DIR}/${1}.org ${SVN_ACCESS_DIR}/${1}
                rm ${SVN_ACCESS_DIR}/${1}.org
                echo "User: ${3} sucessfuly added"
fi

}


#
# Remove a user from a svn group
#
RemoveUserSVNGroup(){
if [ $# -ne 3 ];then
	echo "You need to use -P -G -U together"
	echo "mysvnadmin -P project -G group -U user -D"
	exit 1

	elif [ ! -f ${APACHE_PROJECT_CONF}/${1} ];then
		echo "There is no such project: ${1}"
		exit 1
	else
        	SearchSVNGroup $1 $2
fi

if `grep "\<${1}\>" $arq | grep "${2}" >/dev/null`; then
        # Remove User and comma
        (sed "/^${1}/s/${2}//;s/\,.$//" $arq | sed "s/,[,]*\ *,/,/g" ) > ${arq}.org
        cp ${arq}.org ${arq}
        rm ${arq}.org
fi
}



#
# Check Variables config
#
if [ ! -f ${SVN_PASS_FILE} ];then
	echo "File: ${SVN_PASS_FILE} don't exist"
	echo "You should change the variable  \${SVN_PASS_FILE}"
	exit 1
fi

if [ ! -f ${APACHE_HTPASS_CMD} ];then
	echo "File:  ${APACHE_HTPASS_CMD} don't exist"
	echo "You should change the variable \${APACHE_HTPASS_CMD}"
	exit 1
fi

if [ ! -d ${SVN_ACCESS_DIR} ] ;then
	echo "Directory: ${SVN_ACCESS_DIR} don't exist"
	echo "You should change the variable  \${SVN_ACCESS_DIR}"
	exit 1
fi

if [ ! -d ${SVN_ROOT_HOME} ] ;then
	echo "Directory: ${SVN_ROOT_HOME} don't exist"
	echo "You should change the variable \${SVN_ROOT_HOME}"
	exit 1
fi

if [ ! -d ${APACHE_SERVER_CONF} ] ;then
	echo "Directory: ${APACHE_SERVER_CONF} don't exist"
	echo "You should change the variable \${APACHE_SERVER_CONF}"
	exit 1
fi



# 
# Main Program
#

#clear 
if [ $(id -u) -eq 0 ];then
	while getopts 'a:c:t:g:P:G:U:ADvh' Option
		do
        		case $Option in
        		  a ) username=$OPTARG
			      AddApacheUser $username ;; 
        		  c ) repos_name=$OPTARG ;;
        		  t ) APACHE_TEMPLATE=$OPTARG
				if [ -z ${repos_name} ];then
				echo "You need to use -c with -t"
				exit 1
			        fi
			      CreateSVNRepos $repos_name $APACHE_TEMPLATE;;  
        		  g ) username=$OPTARG
				AddApacheUserGenpass $username;;
			  P ) PROJECT_NAME=$OPTARG;;
			  G ) SVNGROUP_NAME=$OPTARG;;
			  U ) SVNUSER_NAME=$OPTARG;;
			  A ) 
			     AddUserSVNGroup \
			     ${PROJECT_NAME} ${SVNGROUP_NAME} ${SVNUSER_NAME}
			  	;;
			  D ) ;;
        		  v ) echo "$0 $version";;
        		  h) usage;;
        		  \? ) usage
			  	break;;
        		esac
		done
	shift $(($OPTIND -1))
	else
	echo "You need root permission"
	exit 1
fi
